import React from 'react'
import {connect} from 'react-redux'
import { Form, Select, message, Button, Row, Col, Alert, Spin, Input } from 'antd';
import interfaceService from "containers/financial-account/interface-definition/interface-service";
import {deepFullCopy, messages} from "share/common";
import Chooser from "components/chooser";
const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
  labelCol: {span: 8},
  wrapperCol: {span: 14},
};

class dataRule extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      record: {},
      saveLoading: false,
      accountingObject: {},
      optionLoading: false,
      optionList: [],
      accountingSceneDetailList: [],
      focusIndex: -1
    }
  }

  componentWillMount() {

  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showSlideFrame === this.props.showSlideFrame)
      return;
    if (!nextProps.showSlideFrame) {
      this.props.form.resetFields();
      this.setState({focusIndex: -1});
      return !1;
    }
    this.props.form.resetFields();
    this.setState({ record: nextProps.editRecord },() => {
      const { record } = this.state;
      this.setState({
        accountingObject: {
          accountCode: record.accountingCode,
          accountDesc: record.accountingName,
          id: record.accountingId
        },
        accountingSceneDetailList: record.accountingSceneDetailList ? deepFullCopy(record.accountingSceneDetailList) : []
      })
    });
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err) => {
      if(!err){
        const { record, accountingObject, accountingSceneDetailList } = this.state;
        const { user, tenant, settingMate } = this.props;
        let values = {};
        record.id && (values.id = record.id);
        values.tenantId = tenant.id;
        values.setOfBooksId = settingMate.setOfBooksId;
        values.sceneMappingGroupId = settingMate.id;
        values.accountingCode = accountingObject.accountCode;
        values.accountingName = accountingObject.accountDesc;
        values.accountingId = accountingObject.id;
        values.accountingSceneDetailList = accountingSceneDetailList;
        values.createdBy = user.userOID;
        this.setState({saveLoading: true});
        interfaceService.addObject(values).then(() => {
          this.setState({saveLoading: false});
          this.props.close(true);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(e.response.data.message);
        })
      }
    })
  };

  handleChangeObject = value => {
    this.setState({accountingObject: value[0]});
  };

  handleChangeOption = (item,index) => {
    const { tenant, settingMate } = this.props;
    this.setState({optionLoading: true});
    interfaceService.getValueList(tenant.id,settingMate.setOfBooksId,item.type).then(res => {
      this.setState({
        optionLoading: false,
        optionList: res.data.data[0].ledElementValueDTOList || [],
        focusIndex: index
      });
    }).catch(e => {
      this.setState({optionLoading: false});
      message.error(e.response.data.errorCode);
    });
  };

  handleChange = (value,index) => {
    const { optionList, accountingSceneDetailList, record } = this.state;
    const { settingMate } = this.props;
    optionList.map(item => {
      let temp = (!item.id || item.id === '-1') ? item.showName : item.id;
      if (temp === value) {
        if(Object.keys(record).length){
          accountingSceneDetailList[index].refElementTargetId = item.id;
          accountingSceneDetailList[index].refElementTargetValue = item.showName;
          accountingSceneDetailList[index].refElementTargetCode = item.code;
        } else {
          accountingSceneDetailList[index] = {
            refElementTargetId: item.id,
            refElementTargetValue: item.showName,
            refElementTargetCode: item.code,
            elementId: settingMate.sceneElementSimpleDTOList[index].sceneElementId,
            elementName: settingMate.sceneElementSimpleDTOList[index].elementName,
            elementCode: settingMate.sceneElementSimpleDTOList[index].elementCode,
            sceneMappingGroupId: settingMate.id
          }
        }
      }
    });
    this.setState({accountingSceneDetailList});
  };

  handleChangeInput = (value,index) => {
    const { accountingSceneDetailList, record } = this.state;
    const { settingMate } = this.props;
    if(Object.keys(record).length){
      accountingSceneDetailList[index].refElementTargetValue = value.target.value;
      accountingSceneDetailList[index].refElementTargetCode = value.target.value;
    } else {
      accountingSceneDetailList[index] = {
        refElementTargetValue: value.target.value,
        refElementTargetCode: value.target.value,
        elementId: settingMate.sceneElementSimpleDTOList[index].sceneElementId,
        elementName: settingMate.sceneElementSimpleDTOList[index].elementName,
        elementCode: settingMate.sceneElementSimpleDTOList[index].elementCode,
        sceneMappingGroupId: settingMate.id
      };
    }
  };

  render(){
    const { record, saveLoading, accountingObject, optionLoading, optionList, accountingSceneDetailList, focusIndex } = this.state;
    const { settingMate } = this.props;
    const { getFieldDecorator } = this.props.form;
    return(
      <div>
        <Form style={{marginTop:'10px'}}>
          <h2>{messages('financial-account.key114')/*匹配科目*/}</h2>
          <FormItem label={messages('financial-account.key115')/*科目*/} {...formItemLayout} style={{marginBottom: '10px'}}>
            {getFieldDecorator('accountingCode', {
              rules: [{
                required: true, message: messages('common.please.select')/*请选择*/,
              }],
              initialValue: record.accountingCode ? [{accountCode: record.accountingCode}] : []
            })(
              <Chooser type="select_object"
                       valueKey="accountCode"
                       labelKey="accountCode"
                       listExtraParams={{
                         setOfBooksId: settingMate.setOfBooksId
                       }}
                       onChange={this.handleChangeObject}
                       single/>
            )}
          </FormItem>
          <Row style={{margin: '10px 0px'}}>
            <Col span={8}>{messages('financial-account.key116')/*科目名称：*/}</Col>
            <Col span={14}>{accountingObject ? accountingObject.accountDesc : '-'}</Col>
          </Row>
          <h2>{messages('financial-account.key117')/*请选择需要匹配的映射字段*/}</h2>
          <Alert showIcon type='info' message={messages('financial-account.key118')/*映射字段可在编辑匹配组时进行设置。*/} style={{margin:'10px 0px'}}/>
          {
            settingMate.sceneElementSimpleDTOList && settingMate.sceneElementSimpleDTOList.map((item,index) => {
              return (
                item.type ?
                  <FormItem label={item.elementName} {...formItemLayout}>
                    {getFieldDecorator(`arg-${index}`, {
                      rules: [{
                        required: true, message: messages('common.please.select')/*请选择*/,
                      }],
                      initialValue: record.accountingSceneDetailList ? (record.accountingSceneDetailList[index].refElementTargetId || accountingSceneDetailList[index].refElementTargetValue) : undefined
                    })(
                      <Select notFoundContent={optionLoading ? <Spin size="small"/> : messages('pay.key6'/*无匹配结果*/)}
                              showSearch
                              filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                              }
                              placeholder={messages('common.please.select')/*请选择*/}
                              onChange={value => this.handleChange(value, index)}
                              onBlur={() => {this.setState({optionList: [], focusIndex: -1})}}
                              onFocus={() => this.handleChangeOption(item,index)}>
                        {
                          accountingSceneDetailList[index] && focusIndex !== index ? (<Option key={accountingSceneDetailList[index].refElementTargetId || accountingSceneDetailList[index].refElementTargetValue}>
                            {`${accountingSceneDetailList[index].refElementTargetCode ? `${accountingSceneDetailList[index].refElementTargetCode}-`: ''}${accountingSceneDetailList[index].refElementTargetValue}`}
                          </Option>) : optionList.map(option => {
                            return <Option key={option.id && option.id !== '-1' ? option.id : option.showName}>{option.code ? `${option.code}-${option.showName}` : option.showName}</Option>
                          })
                        }
                      </Select>
                    )}
                  </FormItem> : <FormItem label={item.elementName} {...formItemLayout}>
                    {getFieldDecorator(`arg-${index}`, {
                      rules: [{
                        required: true, message: messages('common.please.enter')/*请输入*/,
                      }],
                      initialValue: record.accountingSceneDetailList ? record.accountingSceneDetailList[index].refElementTargetValue : undefined
                    })(
                      <Input onChange={value => this.handleChangeInput(value, index)} placeholder={messages('common.please.enter')/*请输入*/}/>
                    )}
                  </FormItem>
              )
            })
          }
        </Form>
        <div className="footer-operate" style={{backgroundColor:'#ffffff',left:'0px'}}>
          <Button type="primary"  onClick={this.handleSave} style={{margin:'0px 10px'}} loading={saveLoading}>{messages('common.save')/*保存*/}</Button>
          <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    settingMate: state.financialAccount.settingMate,
    user: state.login.user,
    tenant: state.login.tenant
  }
}

const wrappedDataRule = Form.create()(dataRule);
export default connect(mapStateToProps)(wrappedDataRule);
